#ifndef LOG_H
#define LOG_H
#include <QtWidgets>
#include <QThread>
#include <QDebug>

class Log : public QThread
{
    Q_OBJECT

public:
    enum LogLevel {
        Verbose,
        Debug,
        Info,
        Warning,
        Error,
        Fatal,
    };

    ~Log();
    static Log& getInstance(){
        if(NULL == instance){
            mutex.lock();
            if(NULL == instance){
                instance = new Log();
            }
            mutex.unlock();
        }
        return *instance;
    }

    static void release(){
        if(instance != NULL){
            mutex.lock();
            instance->running = false;
            instance->quit();
            instance->wait();
            delete instance;
            instance = NULL;
            mutex.unlock();
        }
    }

    static void log(LogLevel level, const char * file,const char * function, int line,const char* data, ...);
    bool running;

    void closeFile(void);
    void createFile(QString filePath);
    void newFile(QString fileName = "", QString filePrefix = "log/");

private:
    explicit Log(QString fileName = "", QString filePrefix = "log/");
    Log(const Log&other); //拷贝构造函数
    Log& operator=(const Log&other); //赋值运算操作符
    static QMutex mutex;
    static Log* instance;
    static QReadWriteLock rwlock;
    static QList<QString*> list;
    QFile *logFile;
    QMutex mutexFile;

protected:
    virtual void run();
};

#define LOGV(...)    Log::log(Log::Verbose,__FILE__,__FUNCTION__,__LINE__, __VA_ARGS__)
#define LOGD(...)    Log::log(Log::Debug,__FILE__,__FUNCTION__,__LINE__, __VA_ARGS__)
#define LOGI(...)    Log::log(Log::Info,__FILE__,__FUNCTION__,__LINE__, __VA_ARGS__)
#define LOGW(...)    Log::log(Log::Warning, __FILE__,__FUNCTION__, __LINE__,__VA_ARGS__)
#define LOGE(...)    Log::log(Log::Error,__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__)
#define LOGF(...)    Log::log(Log::Fatal,__FILE__,__FUNCTION__,__LINE__, __VA_ARGS__)

#endif // LOG_H
